package webapi

import (
	"ims/app/dao"
	"ims/app/model"
	"ims/app/ws"
	"ims/tools"
	"ims/tools/response"
	"time"

	"github.com/gogf/gf/errors/gerror"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/text/gstr"
	"github.com/gogf/gf/util/gconv"
)

var Kefu = kefuApi{}

type kefuApi struct{}

func (c *kefuApi) Login(r *ghttp.Request) {

	// data, _ := r.GetJson()
	account := r.GetString("account", "")
	password := r.GetString("password", "")
	isApp := r.GetInt("is_app", 0)
	clientId := r.GetString("client_id", "")

	g.Log().Debug(account, password, isApp, clientId)
	//检测账号是否存在
	data, err := c._checkAccount(r, account, password, isApp)

	if err != nil {
		response.JsonResponse(r, g.Map{
			"status": gerror.Code(err),
			"msg":    err.Error(),
			"data":   err,
		})
	}

	response.JsonResponse(r, g.Map{
		"status": 200,
		"msg":    "登陆成功",
		"data":   data,
	})

}
func (*kefuApi) _checkAccount(r *ghttp.Request, account string,
	password string, isApp int) (map[string]interface{}, error) {
	var kefuInfo model.ChatService

	if dao.ChatService.M.Where("account=?", account).Scan(&kefuInfo) != nil {
		return nil, gerror.NewCode(1001, "没有此用户")
	}
	if !tools.PasswordVerify(password, kefuInfo.Password) {
		return nil, gerror.NewCode(1002, "账号或密码错误")
	}
	if kefuInfo.Status == 0 {
		return nil, gerror.NewCode(1002, "您已被禁止登录")

	}

	token, _ := tools.JwtMakeToken(map[string]interface{}{
		"id": kefuInfo.Id, "type": "kefu",
	})

	kefuInfo.Ip = r.GetClientIp()
	kefuInfo.Status = 1
	if kefuInfo.IsApp == 0 {
		kefuInfo.IsApp = isApp
	}

	kefuInfo.Online = 1
	//更新客服数据
	dao.ChatService.M.Where("id=?", kefuInfo.Id).
		Fields("ip,status,is_app, online").
		Update(kefuInfo)

	return map[string]interface{}{
		"token":    token,
		"exp_time": time.Now().Add(30 * 24 * time.Hour * time.Duration(1)).Unix(),
		"kefuInfo": dao.GetChatServiceByIdOrUserId(gconv.String(kefuInfo.Id), gconv.String(kefuInfo.Id)),
	}, nil
}

// 获取当前客服和所有访客用户的列表
// 对应路由 /api/kefu/user/record
func (*kefuApi) GetKefuRecordList(r *ghttp.Request) {
	//从请求的url参数获取
	nickname := r.GetString("nickname")
	labelId := gstr.Split(r.GetString("labelId"), ",")
	groupId := gstr.Split(r.GetString("groupId"), ",")
	is_tourist := r.GetString("is_tourist")
	limit := r.GetInt("limit", 15)
	page := r.GetInt("page", 1)
	//从中间件里面或得kefuid
	kefuId := r.GetString("kefuId")
	info := dao.GetChatServiceById(kefuId)

	g.Log().Debug(info)

	data := dao.GetChatKefuRecord(ws.APPID, info.UserId, nickname, is_tourist, labelId, groupId, limit, page)
	response.JsonResponse(r, g.Map{
		"status": 200,
		"msg":    "ok",
		"data":   data,
	})
}
